package com.starblink.brand.widget

import android.content.Context
import android.util.AttributeSet
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.postDelayed
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.load.DecodeFormat
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.ext.load
import com.starblink.brand.databinding.WidgetProductCardBrand1Binding
import com.starblink.brand.search.bean.RvProductWapper
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.store.StoreManager

/**
 * 品牌搜索商品卡片View
 */
class ProductCardBrandView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0,
) : ConstraintLayout(context, attrs, defStyleRes) {
    //===传参数据START
    lateinit var product: ProductF
    lateinit var activity: FragmentActivity
    var trackPage: Int = 0
    var position: Int = 0
    var brandName: String = ""
    var brandId: Int? = null
    var searchTerm: String = ""
    var searchResultEmpty: Boolean = false
    var simpleView = true // true-图片；false图文
    //===传参数据END

    // Widget视图
    val binding: WidgetProductCardBrand1Binding =
        WidgetProductCardBrand1Binding.inflate(inflater, this)

    init {
        // 使用ViewBinding.inflate方式添加Widget视图，root View的padding等属性会失效
        setPadding(0, 0, 0, 20.dp)
//        setBackgroundColor(color(com.starblink.basic.style.R.color.gu_blue_300))
//        orientation = VERTICAL
    }

    /**
     * 商品卡片绑定数据
     */
    fun bindProduct(
        activity: FragmentActivity,
        productWapper: RvProductWapper, // 商品对象
        trackPage: Int, // 埋点页面
        position: Int, // Item列表位置
        brandName: String,
        brandId: Int? = null,
        searchTerm: String = "", // 埋点：搜索关键词
        searchResultEmpty: Boolean = false, // 埋点：搜索结果为空
    ) {
        this.product = productWapper.product
        this.activity = activity
        this.trackPage = trackPage
        this.position = position
        this.simpleView = productWapper.showSimpleView
        this.brandName = brandName
        this.brandId = brandId
        this.searchTerm = searchTerm
        this.searchResultEmpty = searchResultEmpty

        // 埋点：商品卡片 曝光，点击
        trackData(
            page = trackPage,
            element = SpmElementDef.ProductDetailNewBody,
            traceInfo = product.traceInfo,
            params = trackMap(),
            businessSuffixID = businessSuffixId(product)
        )
        setOnClickListener {
            StoreManager.navigationToProductWebPage(activity, product)
        }

        initBigOrSmallCard(productWapper.bigCard)

        //主图
        binding.ivProductPic.run {
            load(product.mainImg ?: "", format = DecodeFormat.PREFER_RGB_565)

            setOnLongClickListener {
                BrandProductsFindSimilarPop(
                    activity = activity,
                    product = product,
                    anchorView = it,
                    spmPageValue = trackPage,
                    addClick = {
                        doCollectProduct()
                    },
                ).showPopupWindow()

                true
            }

            trackData(
                page = trackPage,
                element = SpmElementDef.ProductDetailNewBody,
                traceInfo = product.traceInfo,
                params = trackMap(),
                onlyHit = true,
                businessSuffixID = businessSuffixId(product)
            )
            setOnClickListener {
                StoreManager.navigationToProductWebPage(activity, product)
            }
        }

        //主图-折扣标签
        binding.tvDiscountTag.visibleOrGone(
            product.disCountInfo?.discountPercent.isNullOrEmpty().not()
        ) {
            text = "-${product.disCountInfo?.discountPercent}"
        }

        // 价格相关
        if (product.disCountInfo != null) {
            binding.layoutDiscountPrice.visible()
            binding.tvPrice.gone()
            // 折扣后价格
            binding.tvPriceAfterDiscount.visibleOrGone(product.price != null) {
                show(
                    product.price!!,
                    product.currency,
                    product.currencySymbol
                )
            }

            // 折扣前价格
            binding.tvPriceOff.visibleOrGone(product.disCountInfo?.underlinePrice != null) {
                show(
                    product.disCountInfo?.underlinePrice!!,
                    product.currency,
                    product.currencySymbol
                )
            }

            // 节省价格
            binding.tvPriceSave.visibleOrGone(product.price != null && product.disCountInfo?.underlinePrice != null) {
                show(
                    Math.max(product.disCountInfo?.underlinePrice!! - product.price!!, 0.0),
                    product.currency,
                    product.currencySymbol
                )
            }
        } else {
            binding.layoutDiscountPrice.gone()
            binding.tvPrice.visible()

            // 原价格
            binding.tvPrice.visibleOrGone(product.price != null) {
                show(
                    product.price!!,
                    product.currency,
                    product.currencySymbol
                )
            }
        }

        // 描述
        binding.tvDescription.visibleOrGone(
            !productWapper.showSimpleView && product.title.isNullOrEmpty().not()
        ) {
            text = product.title
        }

        // 收藏按钮
        binding.ivCollect.run {
            updateCollect(product.collected)
            click { doCollectProduct() }
        }

        // 商品收藏事件处理
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == this.product.id) {
                    this.product.apolloValue("collected", event.collect)
                    updateCollect(this.product.collected)
                }
                product.offerList?.forEach {
                    if (event.id == it?.spuOffer?.id) {
                        it?.spuOffer?.run {
                            apolloValue("collected", event.collect)
                        }
                    }
                }
            }
        }
    }

    /**
     * 初始化大卡或小卡
     */
    private fun initBigOrSmallCard(bigCard: Boolean) {
        var fontScaleFactor = 0f
        // 价格大于3位，每大一位，缩放2
        if (product.price != null && product.disCountInfo?.underlinePrice != null) {
            var save =
                (Math.max(product.disCountInfo?.underlinePrice!! - product.price!!, 0.0)).toInt()
            var length = 0
            do {
                save = save / 10
                length++
            } while (save > 0)
            if (length > 3) {
                fontScaleFactor = (length - 3) * 2f
            }
        }

        if (!bigCard) {
            // 小图
            binding.layoutProductPic.setCornerRadius(8.dp.toFloat())
            binding.ivProductPic.enableCorner(6.dp)

            binding.tvDiscountTag.textSize = 12f
            binding.ivAddToBoard.updateLayoutParams<LinearLayout.LayoutParams> {
                width = 16.dp
                height = 16.dp
            }
            binding.tvAddToBoard.textSize = 12f

            binding.tvPriceOff.setTextSizes(10f, 10f, 8f)
            binding.tvPriceAfterDiscount.setTextSizes(14f, 12f, 12f)
            binding.vSave.textSize = 10f
            binding.tvPriceSave.setTextSizes(
                12f - fontScaleFactor,
                10f - fontScaleFactor,
                10f - fontScaleFactor
            )
            binding.tvPrice.setTextSizes(14f, 12f, 12f)

            binding.tvDescription.textSize = 12f
        } else {
            // 大图
            binding.layoutProductPic.setCornerRadius(16.dp.toFloat())
            binding.ivProductPic.enableCorner(12.dp)

            binding.tvDiscountTag.textSize = 14f
            binding.ivAddToBoard.updateLayoutParams<LinearLayout.LayoutParams> {
                width = 24.dp
                height = 24.dp
            }
            binding.tvAddToBoard.textSize = 14f

            binding.tvPriceOff.setTextSizes(12f, 12f, 10f)
            binding.tvPriceAfterDiscount.setTextSizes(16f, 14f, 14f)
            binding.vSave.textSize = 12f
            binding.tvPriceSave.setTextSizes(
                14f - fontScaleFactor,
                12f - fontScaleFactor,
                12f - fontScaleFactor
            )
            binding.tvPrice.setTextSizes(16f, 14f, 14f)

            binding.tvDescription.textSize = 14f
        }
    }

    /**
     * 收藏商品
     */
    private fun doCollectProduct() {
        CommonMutateManage.collectProduct(
            ctx = context,
            id = product.id!!,
            type = product.type,
            scope = activity.lifecycleScope,
            collected = (product.collected == true),
            refreshState = {
                updateCollect(product.collected != true)
            }
        ) { it, collected ->
            if (it) {
                // 收藏或取消收藏成功，更新数据
                product.apolloValue("collected", collected)

                // 收藏成功，显示Add To Board提示(显示时隐藏收藏按钮)
                binding.layoutAddToBoard.visibleOrGone(product.collected == true) {
                    this.animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
                        .apply {
                            duration = 500L
                        }
                    this.animation?.start()
                    this.postDelayed(3000L) {
                        this.gone()
                    }
                    this.setOnClickListener {
                        WishlistAddBottomDialog.showAddListDialog(
                            context,
                            batchPros = arrayListOf(
                                BatchProductArrEntry(
                                    id = product.id ?: "",
                                    type = product.type,
                                    url = product.mainImg ?: ""
                                )
                            ),
                            spmPageValue = trackPage
                        )
                    }
                }

                // 埋点:商品收藏-点击
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            trackPage,
                            SpmElementDef.ProductDetailNewBodyCollection
                        ),
                        traceInfo = product.traceInfo ?: "",
                        params = trackMap()
                            .plus("result" to if (product.collected == true) "1" else "0")
                    )
                )
            } else {
                // 收藏或取消收藏失败，恢复UI状态
                updateCollect(product.collected)
            }
        }
    }

    // 更新收藏按钮图标
    private fun updateCollect(collected: Boolean?) {
        binding.ivCollect.setImageResource(
            if (collected == true) com.starblink.basic.style.R.drawable.ic_prd_collected1
            else com.starblink.basic.style.R.drawable.ic_prd_collect1
        )
    }

    // 埋点参数map
    private fun trackMap(): Map<String, String> {
        val map: MutableMap<String, String> = SpmTrackHandler.trackProductMap(position, product)
        map.remove("type")
        map["brandName"] = "$brandName"
        map["pattern"] = "${if (simpleView) "bigImg" else "img&text"}"
        brandId?.let {
            map["brandId"] = "$brandId"
        }
        if (searchTerm.isNullOrEmpty().not()) {
            map["searchTerm"] = "$searchTerm"
            map["searchType"] = "normal"
        }
        if (searchResultEmpty) {
            map["feedType"] = "recommend"
        }
        return map
    }
}